package com.example.demo18_custom_concurrentsession.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义 LoginFilter 代替 UsernamePasswordAuthenticationFilter
 * 使用 json 格式的参数登录，而不是默认的表单格式参数登录
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        if ("application/json".equalsIgnoreCase(request.getContentType()) ||
                "application/json;charset=UTF-8".equalsIgnoreCase(request.getContentType())) {
            Map<String, String> loginData = new HashMap<>();
            try {
                loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            } catch (IOException e) {
                throw new AuthenticationServiceException("登录的 json 数据异常");
            }
            String username = loginData.get("username");
            String password = loginData.get("password");
            username = username == null ? "" : username;
            password = password == null ? "" : password;
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            // Allow subclasses to set the "details" property
            setDetails(request,authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }else {
            return super.attemptAuthentication(request, response);
        }
    }
}
